package com.tlc.servlet;
import com.tlc.bean.Book;
import com.tlc.dao.BookDao;
import com.tlc.util.PageUtils;
import com.tlc.util.UploadFiles;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.*;
import java.util.List;

@WebServlet("/BookServlet")
@MultipartConfig
public class BookServlet extends BossServlet {
    //调用dao层的对象
    private BookDao bookDao = new BookDao();

    /**
     * 添加图书
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void addBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收请求
        String sname = request.getParameter("sname");
        //非空提交
        if ("".equals(sname)) {
            request.getRequestDispatcher("addBooks.jsp").forward(request, response);
        }
        double price = Double.parseDouble(request.getParameter("price"));
        String auther = request.getParameter("auther");
        String phouse = request.getParameter("phouse");
        String dtime = request.getParameter("dtime");
        int bcount = Integer.parseInt(request.getParameter("bcount"));
        String nsale = request.getParameter("nsale");
        String classify = request.getParameter("classify");
        String[] strs = request.getParameterValues("lang");
        //获取图片
        Part part = request.getPart("cover");
        //调用工具类--获取图片
        String cover = new UploadFiles().loadImage(part);
        //声明一个空字符串
        String lan = "";
        for (String str : strs) {
            lan = lan + str + "#";
        }
        //去掉最后一个#号
        String lang = lan.substring(0, lan.length() - 1);
        //封装属性
        Book book = new Book(sname, price, auther, phouse, dtime, bcount, nsale, classify, lang, cover);
        //调用Dao层
        int num = bookDao.addDao(book);
        //请求响应
        PrintWriter pw = response.getWriter();
        if (num > 0) {
            pw.print("<script>alert('添加成功！')</script>");

        } else {
            pw.print("<script>alert('添加失败！')</script>");
        }
    }

    /**
     * 查询图书
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void queryBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收搜索的数据
        String sname = request.getParameter("sname");
        String classify = request.getParameter("classify");

        // 当前页容量
        String ps = request.getParameter("pageSize");

        //获取总记录数
        String tc = request.getParameter("totalCount");
        String currentPage;
        if ("0".equals(tc)) {
            currentPage = null;
        } else {
            currentPage = request.getParameter("currentPage");
        }
        int pageSize = 0;
        if (ps == null) {
            //实现分页查询
            pageSize = 5;//页容量
        } else {
            pageSize = Integer.parseInt(ps);
        }

        //总记录数Dao层
        int totalCount = bookDao.infoCount(sname, classify);
        PageUtils pu = new PageUtils(pageSize, totalCount, currentPage);
        //行下标
        int startIndex = pu.getStartIndex();

        //调用Dao层
        List<Book> list = bookDao.queryDao(sname, classify, startIndex, pageSize);

        //使用作用域接收数据库的数据
        request.setAttribute("list", list);
        //保存搜索框的数据
        request.setAttribute("sname", sname);
        request.setAttribute("classify", classify);
        request.setAttribute("pageSize", pageSize);
        //保存PageUtils对象
        request.setAttribute("pu", pu);
        //调转界面queryBooks.jsp
        request.getRequestDispatcher("queryBooks.jsp").forward(request, response);
    }

    /**
     * 删除图书
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收请求
        int sid = Integer.parseInt(request.getParameter("id"));
        String cover = request.getParameter("cover");
        String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");

        File file = new File("E://JAVA/image/" + cover);
        if (file.exists()) {
            file.delete();
        }

        //调用Dao层
        int i = bookDao.deleteDao(sid);

        //给出响应
        //1.提示信息
        PrintWriter pw = response.getWriter();
        if (i > 0) {
            //删除成功，调用查询更新数据
            queryBooks(request, response);
        } else {
            pw.print("<script>alert('删除失败！')</script>");
        }
    }

    /**
     * 图书详情
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void bookdetails(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收请求
        int sid = Integer.parseInt(request.getParameter("sid"));
        //接收flag值
        String flag = request.getParameter("flag");

        //获取当前页
        String currentPage = request.getParameter("currentPage");
        //获取页容量
        String pageSize = request.getParameter("pageSize");

        //调用Dao层
        Book bo = bookDao.detailsDao(sid);

        //将对象保存在域对象中【这里使用request是因为每次请求数据都会有更新，为了保证数据的更新】
        request.setAttribute("book", bo);
        HttpSession session = request.getSession();
        session.setAttribute("crrentPage", currentPage);
        session.setAttribute("pageSize", pageSize);
        //根据用户传过来的值判断跳转的页面
        if ("delete".equalsIgnoreCase(flag)) {
            //跳转页面bookDetails.jsp
            request.getRequestDispatcher("bookDetails.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("changeBook.jsp").forward(request, response);
        }
    }

    /**
     * 修改图书
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void changeBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收请求
        int sid = Integer.parseInt(request.getParameter("sid"));
        String sname = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        String auther = request.getParameter("auther");
        String phouse = request.getParameter("phouse");
        String dtime = request.getParameter("dtime");
        int bcount = Integer.parseInt(request.getParameter("bcount"));
        String nsale = request.getParameter("nsale");
        String classify = request.getParameter("clas");
        String[] strs = request.getParameterValues("lang");
        Part part = request.getPart("cover");
        String oldcover = request.getParameter("oldcover");
        //获取页容量和当前页
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");
        //判断是否有文件上传
        File file = new File("E:/JAVA/image/" + oldcover);
        String cover = "";
        if (part.getSize() > 0) {
            //调用上传文件工具类
            cover = new UploadFiles().loadImage(part);
            //同时删除旧的文件
            file.delete();

        } else {
            cover = oldcover;
        }
        //遍历字符数组
        String st = "";
        String lang = null;
        if (strs != null) {
            for (String str : strs) {
                st = st + str + "#";
            }
            lang = st.substring(0, st.length() - 1);
        }

        //封装数据
        Book book = new Book(sid, sname, price, auther, phouse, dtime, bcount, nsale, classify, lang, cover);

        int i = bookDao.changeDao(book);
        //给出响应
        PrintWriter pw = response.getWriter();
        if (i > 0) {
            queryBooks(request, response);
//            pw.print("<script>alert('修改成功！')</script>");
        } else {
            pw.print("<script>alert('修改失败！')</script>");
        }
    }
}